<template>
  <div class="table-default">
    <el-button  type="primary" @click="goback">返回</el-button>
    <el-button type="warning" @click="choseHandler" class="choseBtn">选择采购订单 </el-button>

    <el-button type="success" @click="addSupplier(ruleFormRef)">保存</el-button>

    <h2 style="padding: 20px 7px">供货商送货单-新增</h2>
    <div class="info" style="color: #999; padding: 0px 7px 20px 7px">
      <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
      <span>新增送货单：先选择采购订单，再输入对应箱号和送货时间</span>
    </div>

    <el-form :model="remarkForm" label-width="60px" ref="form">
      <el-form-item label="备注" prop="remarks">
        <div class="formItem">
          <div style="width: 20%">
            <el-input v-model="remarkForm.remarks" name="remarks" clearable />
          </div>

          <div class="batchIpt" v-if="tableForm.tableData.length != 0">
            <span style="width:100px;margin-right: 5px;">批量输入箱数:</span><el-input v-model="batchNumber" placeholder="批量输入箱数" clearable style="width: 150px;margin-right: 20px;" />
            批量输入日期: <el-date-picker v-model="batchdeliverydate" type="date" value-format="YYYY-MM-DD" placeholder="批量输入日期" style="margin-left: 20px" clearable />
          </div>
        </div>
      </el-form-item>

      <el-form-item prop="detailscheck_all">
        <el-dialog v-model="dialogTableVisible" title="选择采购订单" width="95%" style="height: 90vh" destroy-on-close>
          <!-- <openPurchase @send-data="getData" :checkList="checkList" @send-query="getquery"></openPurchase> -->
          <PurchaseOrderVue @send-data="getData" @send-query="getquery"></PurchaseOrderVue>
        </el-dialog>
      </el-form-item>
      <div class="tab-view">
        <el-button class="delBtn" type="danger" @click="clearHandler" v-if="tableForm.tableData.length != 0" v-loading.fullscreen.lock="fullscreenLoading" >清空</el-button>

        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="供货商送货明细" name="purchase">
            <el-form :model="tableForm" label-width="100px" :rules="rules" ref="ruleFormRef">
              <el-table :data="tableForm.tableData" border>
                <el-table-column prop="fbillno" label="采购订单" min-width="200" fixed="left" />
                <el-table-column prop="fmaterialid" label="品号" min-width="130" />
                <el-table-column prop="fmaterialname" label="品名" min-width="200" />
                <el-table-column prop="fqty" label="数量" width="60">
                  <template #default="scope">
                    {{ Number(scope.row.fqty) }}
                  </template>
                </el-table-column>

                <el-table-column prop="quantity" label="暂收数量" width="200">
                  <template #default="scope">
                    <el-form-item :prop="'tableData.' + scope.$index + '.quantity'" :rules="rules.quantity">
                      <el-input-number v-model="scope.row.quantity" :min="0" />
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="number" label="箱数" min-width="180">
                  <template #default="scope">
                    <el-form-item :prop="'tableData.' + scope.$index + '.number'" :rules="rules.number">
                      <el-input-number v-model="scope.row.number" :min="1" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="actual_number" label="实际到货箱数" min-width="180">
                <template #default="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.actual_number'" :rules="rules.actual_number">
                    <el-input-number v-model="scope.row.actual_number" :min="1" />
                  </el-form-item>
                </template>
              </el-table-column> -->
                <el-table-column prop="deliverydate" label="交货日期" width="250">
                  <template #default="scope">
                    <el-form-item :prop="'tableData.' + scope.$index + '.deliverydate'" :rules="rules.deliverydate">
                      <el-date-picker v-model="scope.row.deliverydate" type="date" value-format="YYYY-MM-DD"	 placeholder="选择送货日期" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="fsupplierid_number" label="供应商送编码" min-width="120" />
                <el-table-column prop="fsupplierid_name" label="供应商名称" min-width="120" />
                <el-table-column prop="fownerid_name" label="组织名称" min-width="120" />
                <el-table-column prop="fprovidercontactid" label="联系人" min-width="100" />
                <el-table-column prop="fproviderphone" label="联系电话" min-width="120" />
                <el-table-column prop="fentryid" label="采购序号" min-width="80" />
                <el-table-column prop="fmaterialmodel" label="规格" min-width="150" />
                <el-table-column prop="fmodel" label="型号" min-width="150" />
                <el-table-column prop="funitid_name" label="单位" min-width="80" />
                <el-table-column label="操作" fixed="right" min-width="100">
                  <template #default="scope">
                    <el-button type="danger" @click="delHandler(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
  </div>
</template>



<script lang="ts" setup>
import { ref, reactive, onUpdated, watch } from 'vue'
import { useCreate } from '/admin/composables/curd/useCreate'
import { useShow } from '/admin/composables/curd/useShow'
import { onMounted } from 'vue'
import openPurchase from './openPurchase.vue'
import PurchaseOrderVue from './openPurchase.vue'
// D:\LHT\work\catch-admin\modules\Purchasing\views\purchaseorder\index.vue
import http from '/admin/support/http'
import { useRouter, useRoute } from 'vue-router'
import categoryTable from './categoryTable.vue'
import { ElMessage } from 'element-plus'
import storage from '/admin/utils/storage'
import { InfoFilled } from '@element-plus/icons-vue'
import { delDetailRouter } from '/admin/utils/delDetailRouter'
import emitter from '/admin/utils/emitter'

const router = useRouter()
const route = useRoute()

// const props = defineProps({
//   api: String,
//   supplierId: Number,
//   title: String,
//   tableData: Object,
// })

// const tableData = ref([])
const supplierId = ref()
const newSupplierId = ref()
// const categoryShow = ref(false)

const remarkForm = reactive({
  remarks: '',
})

// supplierId.value = props.supplierId || newSupplierId.value

let tableForm = reactive({
  tableData: [],
})

// if (props.tableData) {
//   remarkForm.remarks = props.tableData.remarks
//   tableForm.tableData = props.tableData.detailscheck_all
// } else {
// remarkForm.remarks = ''
// tableForm.tableData = []
// }

// console.log('明细表格数据：', tableForm.tableData)

// const { formData, form, loading, submitForm, close } = useCreate(props.api, props.primary)
// console.log(formData)

const activeName = ref('purchase')

// if (props.primary) {
//   useShow(props.api, props.primary, formData)
// }

const dialogTableVisible = ref(false)

// let Data = reactive({
//   arr: [],
// })

let allArr = reactive([])
let finished = ref(true)

// const tableData = ref([])

const ruleFormRef = ref()

const rules = reactive({
  quantity: [{ required: true, trigger: 'blur', message: '不能为空' }],
  number: [{ required: true, message: '不能为空', trigger: 'blur' }],
  // actual_number: [{ required: true, message: '不能为空', trigger: 'blur' }],
  deliverydate: [{ required: true, message: '不能为空', trigger: 'change' }],
})
let choseData = ref([])
let getData = data => {
  dialogTableVisible.value = false
  console.log('父组件接受的采购订单数据', data)
  // choseData.value.push(data)
  // console.log(choseData.value);
  // tableForm.tableData = choseData.value.map(item => {
  //   console.log(item);

  //   return {
  //     ...item,
  //     quantity: item.fqty,
  //   }
  // })
  choseData.value = data.map(item => {
    return {
      ...item,
      quantity: item.fqty,
      // fqty: item.fqty,
    }
  })
  console.log(choseData.value)
  choseData.value.forEach(item => {
    // console.log(item)
    // console.log(item.id)
    if (tableForm.tableData.length == 0) {
      tableForm.tableData.push(item)
    }
    if (tableForm.tableData.length != 0 && tableForm.tableData.every(ele => ele.id != item.id)) {
      console.log(item.id)
      tableForm.tableData.push(item)
    }
  })

  // 重新选择
  console.log(tableForm.tableData)
}

let haveID = ref('')
let FormObj = ref({ remarks: ' ', detailscheck_all: [] })

// 添加送货单，获取新ID，生成新品名
const addSupplier = async formEl => {
  if (tableForm.tableData.length == 0) {
    ElMessage.warning('请先选择采购订单！')
  } else {
    console.log('点击添加', tableForm.tableData)
    // 校验同供应商和组织
    let flag = true
    for (let i = 0; i < tableForm.tableData.length; i++) {
      if (tableForm.tableData[0].fsupplierid_number != tableForm.tableData[i].fsupplierid_number) {
        flag = false
        ElMessage.warning('必须是同一供应商')
        break
      }
      if (tableForm.tableData[0].fownerid_number != tableForm.tableData[i].fownerid_number) {
        flag = false
        ElMessage.warning('必须是同一组织')
        break
      }
    }
    if (flag) {
      // console.log('可以提交啦！');
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          for (let i = 0; i < tableForm.tableData.length; i++) {
            let obj = {}
            obj.purchaseorder_id = tableForm.tableData[i].purchaseorder_id
            obj.purchaseorderschedule_id = tableForm.tableData[i].id
            obj.fqty = tableForm.tableData[i].fqty
            obj.deliverydate = tableForm.tableData[i].deliverydate
            obj.quantity = tableForm.tableData[i].quantity
            obj.number = tableForm.tableData[i].number
            obj.actual_number = tableForm.tableData[i].number
            obj.fmasterid = tableForm.tableData[i].fmasterid
            FormObj.value.detailscheck_all[i] = obj
          }
          console.log(remarkForm.remarks)

          FormObj.value.remarks = remarkForm.remarks
          console.log('品名请求数据', FormObj.value)

          // // 新增请求，获取送货单id
          http.post('/purchasing/supplier', FormObj.value).then(r => {
            console.log('新增请求返回数据：', r.data)
            haveID.value = r.data.data
            ElMessage({
              message: r.data.message,
              type: 'success',
            })

            // 新增成功，切换到详情页
            // let routeList = storage.getItem('routeList')
            let routeList = JSON.parse(sessionStorage.getItem('routeList') || '[]')
            // console.log(routeList);

            routeList = routeList.filter(item => item.title != '送货单新增')
            // storage.setItem('routeList', routeList)
            sessionStorage.setItem('routeList', JSON.stringify(routeList))

            emitter.emit('changeSupplierStatus', { OrderStatus: true })

            router.push(`/purchasing/supplierDetail?id=${haveID.value}`)
          })
       
        } else {
          ElMessage({
            message: '有未输入文本！',
            type: 'warning',
          })
        }
      })
    }
  }
}

const editForm = ref({})

const fullscreenLoading = ref(false)

// 删除
const delHandler = item => {
  console.log(item)
  tableForm.tableData = tableForm.tableData.filter(ele => ele.id != item.id)
  // tableForm.tableData.splice(index, 1)
  ElMessage.info('删除后不要忘记提交修改哦!')
  // finished.value = true
}
// 清空
const clearHandler = () => {
  fullscreenLoading.value = true
  tableForm.tableData = []

  fullscreenLoading.value = false
  // tableForm.tableData.splice(index, 1)
  // ElMessage.info('清空后不要忘记提交修改哦!')
  // finished.value = true
}

// let emit = defineEmits(['send-data'])

let queryForm = reactive({})

let checkList = ref([])

let data = ref({
  fbillno: '',
  fsupplierid_name: '',
  state: 0,
})

// 获取采购数据
let getPurchase = data => {
  // if(obj) data.value = obj
  http.get(`/purchasing/popupList`, data).then(r => {
    console.log('弹窗采购数组：', r.data.data)
    checkList.value = r.data.data
    // storage.setItem('purchaseData', resData)
  })
}

let choseHandler = () => {
  getPurchase(data.value)

  dialogTableVisible.value = true
}

// 批量赋值

let batchNumber = ref(null)
let batchdeliverydate = ref(null)

watch(
  () => batchNumber.value,
  (newVal, oldVal) => {
    tableForm.tableData.forEach(item => {
      item.number = newVal
      // item.actual_number = newVal
    })
  },
)
watch(
  () => batchdeliverydate.value,
  (newVal, oldVal) => {
    tableForm.tableData.forEach(item => (item.deliverydate = newVal))
  },
)

let getquery = data => {
  queryForm = data
  console.log('父组件接收的查询数据：', queryForm)
  getPurchase(queryForm)
}

const goback = () => {
  delDetailRouter('送货单新增', '/purchasing/supplier')
}

onUpdated(() => {
  // console.log(allArr)
  // console.log(formData.value)
})
</script>

<style>
.tab-view {
  /* border: 1px solid #000; */
  position: relative;
}
.tab-view .delBtn {
  position: absolute;
  right: 1rem;
  top: 0;
  z-index: 99;
}
.batchIpt {
  margin-left: 30px;
  display: flex;
}
.info {
  color: #999;
  padding: 0px 7px 20px 7px;
  display: flex;
  align-items: center;
}
.btnRow {
  margin: 20px;
}
h2 {
  /* margin-left: 10px; */
  text-align: left;
  font-weight: bold;
}
/* .creatClass {
  padding: 0 60px 20px 0;
} */
.formItem {
  width: 100%;
  align-items: center;
  /* background-color: pink; */
  display: flex;
  flex-shrink: 0;
  /* justify-content: space-between; */
  /* justify-content: space-between; */
}

.choseBtn {
  margin: 0 10px;
}
.required {
  transform: translateY(-100px);
  color: red;
}
.demo-tabs {
  margin: 20px 0px 20px 20px;
}
.backBtn {
  margin: 20px 10px;
}
.el-form-item__content {
  margin-left: 0 !important;
}

.el-overlay-dialog {
  top: -70px !important;
}
</style>
